package com.gmako.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.gmako.entity.Adress;
import com.gmako.entity.Businessimg;
import com.gmako.entity.Businessinfo;
import com.gmako.entity.Userinfo;
import com.gmako.service.AddressService;
import com.gmako.service.BusinessinfoService;
import com.gmako.service.UserinfoService;
import com.gmako.utils.ResponseUtils;


@Controller
@RequestMapping("/register.do")
public class RegisterController {
	@Autowired(required=false) 
	private BusinessinfoService businessinfoService;
	
	@Autowired(required = false)
	private AddressService addressService;
	
	@Autowired(required = false)
	private UserinfoService userinfoService;

	
	/**
	 * 显示注册页面
	 * @author yezhenchi
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "method=view")
	public String viewLogin(HttpServletRequest request){	
		return "login";
	}
	
	/**
	 * 显示添加商户详细信息
	 * @author yezhenchi
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "method=viewBusinessDetail")
	public ModelAndView viewBusinessDetail(HttpServletRequest request,
			HttpServletResponse response, Businessinfo businessinfo){
		HttpSession session = request.getSession();
		Userinfo userinfo = (Userinfo)session.getAttribute("loginUser");
		int tag = userinfoService.findBus(userinfo.getId());
		if(tag == 0){
			System.out.println("没传过");
			request.setAttribute("useremail", userinfo.getUseremail());
			List list = addressService.findByProperty(Adress.class,
					"pid", 0);
			request.setAttribute("flist", list);
			Adress ha = (Adress) list.get(0);

			List zlist = addressService.findByProperty(Adress.class,
					"pid", ha.getId());
			request.setAttribute("zlist", zlist);
			return new ModelAndView("businessPostDetailInfo", "list", list);
		}else if(tag == 1){
			System.out.println("上传过");
			//查询信息
			Businessinfo bui  = businessinfoService.findBusinessInfoByUid(userinfo.getId());
			System.out.println(bui.getRealName());
//			int cityA = bui.getCityAdress();
			//根据city代号查询城市和省的名称
//			Adress adress =  addressService.findAdressName(cityA);
//			String ctiyName = adress.getAdressName();
//			Adress adress2 =  addressService.findAdressName(adress.getPid());
//			String pName = adress2.getAdressName();
			request.setAttribute("useremail", userinfo.getUseremail());
//			request.setAttribute("ctiyName", ctiyName);
//			request.setAttribute("pName", pName);
			List list = addressService.findByProperty(Adress.class,
					"pid", 0);
			request.setAttribute("flist", list);
			Adress ha = (Adress) list.get(0);
			List zlist = addressService.findByProperty(Adress.class,
					"pid", ha.getId());
			request.setAttribute("zlist", zlist);
			request.setAttribute("bui", bui);
			request.setAttribute("bid", bui.getId());
			return new ModelAndView("businessPostDetailInfoEdit", "list", list);
		}
		return null;
	
	}
	
	
	
	
	/**
	 * 获取州下得城市
	 * 
	 * @author yezhenchi
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(params = "method=getzList")
	public @ResponseBody
	String getzList(@RequestParam("aid") String aid,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("UTF-8");
		List<Adress> list = addressService.findByProperty(Adress.class,
				"pid", Integer.parseInt(aid));
		JSONArray jsonArray = JSONArray.fromObject(list);
		response.getWriter().print(jsonArray.toString());
		return null;
	}
	
	/**
	 * 提交商户信息
	 * 
	 * @author Warlock
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "method=addBusinessDetail")
	public String addHouseInfo(HttpServletRequest request,
			HttpServletResponse response, Businessinfo businessinfo){
		HttpSession session = request.getSession();
		Userinfo userinfo = (Userinfo)session.getAttribute("loginUser");
		businessinfo.setUid(userinfo.getId());
		businessinfoService.addBusinessInfo(businessinfo);
		Businessimg businessimg = new Businessimg();
		businessimg.setBid(businessinfo.getId());
		if(request.getParameterValues("text")!=null){
			String[] imgs = request.getParameterValues("text");
			for (String img : imgs) {
				if (img != null) {
					businessimg.setImgname(img);
					businessinfoService.save(businessimg);
				}
			}
		}else{
			request.setAttribute("businessId", businessinfo.getId());
			return "successPostBusiness";
		}	
		request.setAttribute("businessId", businessinfo.getId());
		return "successPostBusiness";
	}
	
	
	/**
	 * 修改商户信息
	 * 
	 * @author Warlock
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "method=updateBusinessDetail")
	public String updatBusiness(HttpServletRequest request,
			HttpServletResponse response, Businessinfo businessinfo){
		HttpSession session = request.getSession();
		int bid =Integer.parseInt(request.getParameter("bid"));
		Userinfo userinfo = (Userinfo)session.getAttribute("loginUser");
		businessinfo.setId(bid);
		businessinfo.setUid(userinfo.getId());
		businessinfoService.updateBusinessInfo(businessinfo);
		Businessimg businessimg = new Businessimg();
		businessimg.setBid(businessinfo.getId());
		if(request.getParameterValues("text")!=null){
			System.out.println("传 有图片");
			businessinfoService.delete(businessimg, businessinfo.getId());
			String[] imgs = request.getParameterValues("text");
			for (String img : imgs) {
				if (img != null) {
					businessimg.setImgname(img);
					businessinfoService.save(businessimg);
				}
			}
		}else{
			request.setAttribute("businessId", businessinfo.getId());
			return "successPostBusiness";
		}	
		request.setAttribute("businessId", businessinfo.getId());
		return "successPostBusiness";
//		return null;
	}
	
	/**
	 * 获取绝对路径
	 * 
	 * @param request
	 * @param path
	 * @return
	 */
	public String getRealPath(HttpServletRequest request, String path) {
		return request.getSession().getServletContext().getRealPath(path);
	}

	/**
	 * 生成ID
	 * 
	 * @return
	 */
	public static String generateId() {
		return new Date().getTime() + getRandomString(5);
	}

	/**
	 * 生成随机字符串(数字+字母)
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(3);
			long result = 0;
			switch (number) {
			case 0:
				result = Math.round(Math.random() * 25 + 65);
				sb.append(String.valueOf((char) result));
				break;
			case 1:
				result = Math.round(Math.random() * 25 + 97);
				sb.append(String.valueOf((char) result));
				break;
			case 2:
				sb.append(String.valueOf(new Random().nextInt(10)));
				break;
			}
		}
		return sb.toString();
	}
	
	/**
	 * @author Warlock
	 * 
	 * 商户信息 -----商户图片————上传
	 * 
	 * @throws Exception
	 */
	@RequestMapping(params = "method=upload")
	public void upload(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String path = getRealPath(request, "/images/businessImg/");
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdir();
		}
		//
		// // 缩放图片
		// String zoomPath = getRealPath(request, "images/houseImg/zoom");
		// File dirZoom = new File(zoomPath);
		// if (!dirZoom.exists()) {
		// dirZoom.mkdir();
		// }

		MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
		MultipartFile file = multipart.getFile("Filedata");

		if (file == null || file.isEmpty()) {
			// 文件不存在
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}

		String newFileName = generateId();

		// 原始图片名称
		String y_fileName = file.getOriginalFilename();

		// 原始图片后缀
		String extname = file.getOriginalFilename().substring(
				y_fileName.lastIndexOf("."));

		// 生成图片 名称
		String fileName = newFileName + extname;
		String fromFileStr = dir.getAbsolutePath() + File.separator + fileName;
		FileCopyUtils.copy(file.getBytes(), new File(dir.getAbsolutePath()
				+ File.separator + fileName));
		response.getWriter().print(fileName);
		request.setAttribute("newFileName", fileName);
	}
}
